import axios from "axios";
import router from "@/router";

import { Message, Loading } from "element-ui";

//创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_URL
});

//请求拦截  这里可以做请求前的一些处理
service.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    Promise.reject(error);
  }
);

let timer = null;

// 添加响应拦截器
service.interceptors.response.use(
  response => {
    // 对响应数据做点什么
    // let ruqesturl = response.request.custom.url

    const loading = Loading.service({});
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function() {
      if (loading.custom) {
      } else {
        loading.close();
      }
    }, 500);

    if (
      response.data.data.resultCode &&
      response.data.data.resultCode != "0000" &&
      response.data.data.resultCode != "401" &&
      response.data.data.resultCode != "00001111"
    ) {
      let options = {
        message: response.data.data.resultMessage || "接口异常",
        showClose: true,
        type: "error"
      };

      Message.error(options);
    }

    return response;
  },
  error => {
    const loading = Loading.service({});
    loading.close();

    // 对响应错误做点什么
    try {
      let status = JSON.parse(JSON.stringify(error)).response.status;
      if (status == "500") {
        let options = {
          message: "服务端报错",
          showClose: true,
          type: "error"
        };
        Message.error(options);
      }
    } catch (error) {
      console.log(error);
    }
  }
);

export default service;
